package com.medical.assistant.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import com.medical.assistant.service.AliLLMService;

@RestController
@RequestMapping("/api/qa")
@CrossOrigin
public class QAController {

    @Autowired
    private AliLLMService aliLLMService;

    @GetMapping(produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<ServerSentEvent<String>> qaGet(@RequestParam(required = false) String message) throws JsonProcessingException {
        System.out.println("开始处理 SSE 请求，消息: " + message);
        
        return aliLLMService
                .askLLMStream(message)
                .map(text -> ServerSentEvent.<String>builder()
                        .data((String) text)
                        .build())
                .doOnNext(event -> System.out.println("Controller 发送 SSE: " + event.data() + " | 时间: " + System.currentTimeMillis()))
                .concatWith(Flux.just(ServerSentEvent.<String>builder()
                        .data("[DONE]")
                        .build()))
                .doOnComplete(() -> System.out.println("✅ SSE 流完成，已发送 [DONE] 标记"));
    }
    
    @PostMapping(produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<ServerSentEvent<String>> qaPost(@RequestBody(required = false) String payload) throws JsonProcessingException {
        System.out.println("开始处理 SSE POST 请求，消息: " + payload);
        
        return aliLLMService
                .askLLMStream(payload)
                .map(text -> ServerSentEvent.<String>builder()
                        .data((String) text)
                        .build())
                .doOnNext(event -> System.out.println("Controller 发送 SSE: " + event.data() + " | 时间: " + System.currentTimeMillis()))
                .concatWith(Flux.just(ServerSentEvent.<String>builder()
                        .data("[DONE]")
                        .build()))
                .doOnComplete(() -> System.out.println("✅ SSE 流完成，已发送 [DONE] 标记"));
    }
}